package jdbc.mysql.gzpowernode;

import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

/*
 * sql脚本
 * drop table if exist t_user;
 * create table t_user(
 * name varchar(255) not null,
 * password varchar(255)
 * );
 * insert into t_user(name,password) values("张三","333"),values("李四","333");
 * select * from t_user;
 * */

/*
 * 可以SQL注入
 *
 * */
public class test04 {
    public static void main(String[] args) {
        System.out.println(login(getUserInfo()) ? "登陆成功" : "登录失败");
    }

    //获取用户信息
    public static Map<String, String> getUserInfo() {
        Map<String, String> user = new HashMap<>();
        Scanner s = new Scanner(System.in);
        System.out.println("请输入用户名:");
        String name = s.nextLine();
        System.out.println("请输入密码:");
        String password = s.nextLine();
        user.put("name", name);
        user.put("password", password);


        return user;
    }

    public static boolean login(Map<String, String> user) {
        boolean flag = false;
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            //1.注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            //2.获取连接对象
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/gzpowernode?&useSSL=false", "root", "123456");
            //3.获取数据库操作对象
            stmt = conn.createStatement();
            //4.执行sql语句
            String sql = "select name,password from t_user where name = '" + user.get("name") + "' and password = '" + user.get("password") + "'";
            rs = stmt.executeQuery(sql);
            //5.处理查询结果集
            if (rs.next()) {
                flag = true;
            }

        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            //6.释放资源
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    System.out.println("查询结果集对象未关闭");
                }
            }
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    System.out.println("数据库操作对象未关闭");
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    System.out.println("连接对象未关闭");
                }
            }
        }
        return flag;
    }

}

